<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天窗口</title>
    <link rel="stylesheet" href="css/button.css"/>
    <link rel="stylesheet" href="css/style.css"/>
    <script src="js/socket.io.js"></script>
    <script src="js/js.cookie.min.js"></script>
</head>

<body>
<div id="msg" class="content">

</div>
<div class="sub">
    <div>
        <input id="text"></div>
    <a onclick="to()" class="button button-royal button-large">发送</a>
</div>
</div>
<div id="num" style="position: absolute;right: 10px;top: 10px;">

</div>
</body>
<script>
    //创建TCP连接
    var socket = io('http://10.11.12.84:8008');
    // 连接成功后会监听到
    socket.on('connect', function () {
        // output('<span>连接成功</span>');
    });


    socket.on('connect_failed', function () {
        //output('<span>连接失败！</span>');
    });
    socket.on('message', function (data) {
        console.log(data);
        let severName = data.username;
        let context = data.msg;
        let name = Cookies.get('username');
        let style = ``;
        if (severName == name) {
            let len = getByteLen(context);
            let left = 90;
            left = left - len;
            if (left < 0) {
                left = 20;
                style += `text-align:left;`;
            }
            style += `margin-left:${left}%;`
            console.log(style);
        }
        let msg = `<div class="c-item ${severName == name ? 'c-item-right' : 'c-item-left'}">
        <ul>
            <li>
                 <span class="photo">
                     <img src="https://ybandtwq.gitee.io/blok-img/yys/head.png" />
                </span>
            </li>
            <li>
                <span>${severName}</span>
                <span>${data.time}</span>
            </li>
        </ul>
        <br/>
        <div class="${severName == name ? 'c-content-right' : 'c-content-left'}" style="${style}">
           ${context}
        </div>
    </div>`;
        output(msg);
    });



    function scrollLast() {
        let showContent = document.getElementById("msg");
        showContent.scrollTop = showContent.scrollHeight;
    }

    socket.on('num', function (num) {
        console.log(num);
        let numDiv = document.getElementById('num');
        numDiv.innerText = `当前在线人数:[${num}]`;
    });

    //想要断开连接调用此方法
    function sendDisconnect() {
        socket.disconnect();
    }

    function getByteLen(val) {
        var len = 0;
        for (var i = 0; i < val.length; i++) {
            var a = val.charAt(i);
            if (a.match(/[^\x00-\xff]/ig) != null) {//\x00-\xff→GBK双字节编码范围
                len += 2;
            }
            else {
                len += 1;
            }
        }
        return len;
    }


    //下面的testMessage是自定义的。
    //这里是监听服务端返回的testMessage事件

    function to() {
        let name = Cookies.get('username');
        if (!name) {
            name = prompt("请输入一个用户名");
            if (!name || name.trim() === '') {
                to();
            }
        }
        name = name.trim();
        Cookies.set('username', name);
        let text = document.getElementById('text');
        if (!text.value || text.value.trim() === '') {
            return;
        }
        socket.emit('message', {
            username: name,
            msg: text.value
        });
        text.value = '';
    }

    function output(str) {
        let msg = document.getElementById('msg');
        console.log(msg);
        msg.innerHTML += str;

        window.localStorage.setItem('msg', msg.innerHTML.trim());
        scrollLast();
    }

    scrollLast();

    function init() {
        let msg = window.localStorage.getItem('msg');
        // console.log(msg);
        let len = getByteLen(msg);
        if (len > 1024 * 1024 * 2) {
            window.localStorage.setItem('msg', '');
        }
        if (msg) {
            output(msg);
        }
    }

    document.onkeydown = function (e) {
        if (e.keyCode == 13) {
            to();
        }
    }
    init();
</script>

</html>
